package com.game.run.server;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import com.game.connection.message.Message;
import com.game.connection.server.ServerPlayer;

/**
 * 
 */

/**
 * @author gustavo
 * 
 */
public class ServerMultiplayerGame {

	private int port;

	private ServerSocket server = null;
	private int numConectionMax = 2;
	private int numConectionCount = 0;
	private HashMap<Integer, List<Message>> messages;
	private int stage; //0 wait connection. 1 star game, 2 gaming
	
	
	public ServerMultiplayerGame() {
		stage = 0; 
		messages = new HashMap<Integer, List<Message>>();
		port = 4555;
		try {
			server = new ServerSocket(port);
		} catch (IOException e) {
			System.out.println("Could not listen on port " + port);
			System.exit(-1);
		}
	}

	
	public void startGame(){
		stage = 2;
	}
	
	public void listing() {
		// game life cicle
		while (true) {
			// wait connection 2 players
			switch (stage) {
			case 0:
				esperandoConexao();
				break;
			case 1:
				startGame();
				break;
			case 2:
			default:
				break;
			}
		}

	}

	public void esperandoConexao(){
		if (numConectionCount < numConectionMax) {
			ServerPlayer player;
			try {
				player = new ServerPlayer(numConectionCount++,
						server.accept(), messages);
				Thread t = new Thread(player);
				t.start();
			} catch (IOException e) {
				System.out.println("Accept failed: 4444");
				System.exit(-1);
			}
			System.out.println("wait connection :: " + numConectionCount);
		}

		if(numConectionCount==numConectionMax)
			stage = 1;
	}
	
	public static void main(String[] args) {
		ServerMultiplayerGame gameServer = new ServerMultiplayerGame();
		gameServer.listing();
	
	}
}
